<template>
  <a-modal
    :open="visible"
    title="批量分配角色"
    :confirm-loading="loading"
    @ok="handleSubmit"
    @cancel="handleCancel"
    :width="700"
    ok-text="保存"
    cancel-text="取消"
    centered
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 18 }"
    >
      <a-form-item label="选择员工" name="employeeId">
        <a-select
          v-model:value="formData.employeeId"
          placeholder="请选择员工"
          show-search
          :filter-option="filterOption"
          allow-clear
        >
          <a-select-option
            v-for="employee in employeeList"
            :key="employee.id"
            :value="employee.id"
          >
            {{ employee.name }}（{{ employee.account }}）
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="选择角色" name="roleIds">
        <a-select
          v-model:value="formData.roleIds"
          mode="multiple"
          placeholder="请选择角色（可多选）"
          show-search
          :filter-option="filterOption"
          allow-clear
          :max-tag-count="3"
        >
          <a-select-option
            v-for="role in roleList"
            :key="role.id"
            :value="role.id"
          >
            {{ role.name }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="已选角色" v-if="formData.roleIds && formData.roleIds.length > 0">
        <div class="selected-roles">
          <a-tag
            v-for="roleId in formData.roleIds"
            :key="roleId"
            color="blue"
            closable
            @close="removeRole(roleId)"
          >
            {{ getRoleName(roleId) }}
          </a-tag>
        </div>
      </a-form-item>
    </a-form>

    <a-alert
      message="提示"
      description="批量分配将为选中的员工分配所有选中的角色，如果某个角色关系已存在，将会跳过该关系。"
      type="info"
      show-icon
      style="margin-top: 16px;"
    />
  </a-modal>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { assignRoles } from '@/api/employeeRole'
import { getEmployeeList } from '@/api/employee'
import { getRoleList } from '@/api/role'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:visible', 'success'])

const formRef = ref()
const loading = ref(false)
const employeeList = ref([])
const roleList = ref([])

// 表单数据
const formData = reactive({
  employeeId: undefined,
  roleIds: []
})

// 表单验证规则
const rules = {
  employeeId: [
    { required: true, message: '请选择员工', trigger: 'change' }
  ],
  roleIds: [
    { required: true, type: 'array', min: 1, message: '请至少选择一个角色', trigger: 'change' }
  ]
}

// 监听弹窗显示状态
watch(() => props.visible, (newVal) => {
  if (newVal) {
    fetchEmployees()
    fetchRoles()
  } else {
    resetForm()
  }
})

// 页面加载时获取数据
onMounted(() => {
  fetchEmployees()
  fetchRoles()
})

// 获取员工列表
const fetchEmployees = async () => {
  try {
    const res = await getEmployeeList({ pageNum: 1, pageSize: 1000 })
    employeeList.value = res.data.items
  } catch (error) {
    message.error('获取员工列表失败')
  }
}

// 获取角色列表
const fetchRoles = async () => {
  try {
    const res = await getRoleList({ pageNum: 1, pageSize: 1000 })
    roleList.value = res.data.items
  } catch (error) {
    message.error('获取角色列表失败')
  }
}

// 搜索过滤函数
const filterOption = (input, option) => {
  return option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}

// 获取角色名称
const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role ? role.name : '未知角色'
}

// 移除角色
const removeRole = (roleId) => {
  const index = formData.roleIds.indexOf(roleId)
  if (index > -1) {
    formData.roleIds.splice(index, 1)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    loading.value = true
    
    await assignRoles({
      employeeId: formData.employeeId,
      roleIds: formData.roleIds
    })
    
    message.success('批量分配成功')
    emit('success')
    handleCancel()
  } catch (error) {
    if (error.errorFields) {
      // 表单验证错误
      return
    }
    message.error('批量分配失败')
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  formData.employeeId = undefined
  formData.roleIds = []
}
</script>

<style lang="scss" scoped>
.selected-roles {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  
  .ant-tag {
    margin: 0;
  }
}

:deep(.ant-modal-footer) {
  text-align: center;
}
</style>